package com.edu.bean;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/*
 * @Author:mx
 * @Date:2025/11/7-14:59:53
 */
public class MyIOC {

    //以 map集合的形式 存容器 创建的对象。key是beanId，值是对应的对象
    private Map<String, Object> box;
    //用以 存Properties配置文件中的信息
    private Properties pro;

    public MyIOC(String path) {
        this.box = new HashMap<>();
        this.pro = new Properties();
        readProperties(path);//读取到配置文件，信息存放在pro理
        init();//解析配置文件 并创建对象
    }

    public void init() {
        Set<String> beanIds = pro.stringPropertyNames();
        for (String beanId : beanIds) {
            String className = pro.getProperty(beanId);
            try {
                Class clazz = Class.forName(className);
                Object o = clazz.newInstance();
                box.put(beanId, o);
            } catch (ClassNotFoundException e) {
                System.out.println("类型不存在");
                e.printStackTrace();
            } catch (InstantiationException e) {
                System.out.println("没有无参数构造方法");
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                System.out.println("无参数构造方法不可被访问");
                e.printStackTrace();
            }
        }
    }


    public void readProperties(String path) {
        InputStream inputStream = MyIOC.class.getClassLoader().getResourceAsStream(path);
        try {
            pro.load(inputStream);
        } catch (IOException e) {
            System.out.println("配置文件不存在");
            e.printStackTrace();
        }
    }


    public Object getBean(Class clazz) {
        for (String s : box.keySet()) {
            Object o = box.get(s);
            if (o.getClass() == clazz) {
                return o;
            }
        }
        return null;
    }

    public Object getBean(String beanId) {
        return box.get(beanId);
    }
}
